﻿<template>
    <el-dialog
        :title="titleMap[mode]"
        v-model="visible"
        :width="1400"
        destroy-on-close
        :close-on-click-modal="false"
        :before-close="handleBeforeClose"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
        >
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="出库时间" prop="outStockDate">
                        <el-date-picker
                            v-model="entityObj.outStockDate"
                            :default-time="defaultTime"
                            type="datetime"
                            value-format="YYYY-MM-DD"
                            format="YYYY-MM-DD"
                            placeholder="请输入要货时间"
                            style="width: 100%"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="出库仓库" prop="warehouses">
                        <sc-warehouse-select
                            ref="orgselect"
                            :props="warehouseProps"
                            :selectKeyValue="'warehouseId'"
                            v-model="entityObj.warehouses"
                            :multiple="false"
                            style="width: 100%"
                        ></sc-warehouse-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="出库类型" prop="outStockType">
                        <el-select
                            placeholder="---请选择状态---"
                            v-model="entityObj.outStockType"
                            style="width: 100%"
                        >
                            <el-option label="---请选择---" value />
                            <el-option
                                v-for="item in optionsoutStockType"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="客户名称" prop="customName">
                        <el-input v-model="entityObj.customName" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="创建人" prop="crName">
                        <el-input v-model="entityObj.crName" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="创建时间" prop="crDate">
                        <el-date-picker
                            v-model="entityObj.crDate"
                            :default-time="defaultTime"
                            type="datetime"
                            value-format="YYYY-MM-DD"
                            format="YYYY-MM-DD"
                            placeholder="请输入创建时间"
                            style="width: 100%"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="创建类型" prop="createType">
                        <el-select
                            placeholder="---请选择创建类型---"
                            v-model="entityObj.createType"
                            style="width: 100%"
                        >
                            <el-option label="---请选择---" value />
                            <el-option
                                v-for="item in optionsCreateType"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label-width="120px" label="来源" prop="sourceType">
                        <el-select
                            placeholder="---请选择来源---"
                            v-model="entityObj.sourceType"
                            style="width: 100%"
                        >
                            <el-option label="---请选择---" value />
                            <el-option
                                v-for="item in optionsSourceType"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="备注">
                        <el-input v-model="entityObj.remarks" type="textarea" :rows="2" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px" label="出库信息" prop="outStockItems">
                        <el-button size="small" @click="addMaterial()">新增物料</el-button>
                        <el-button size="small" v-if="entityObj.outStockType==10" @click="addSaleOrder()">选择销售单出库</el-button>
                    </el-form-item>
                </el-col>
  
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="120px">
                        <el-table
                            :data="entityObj.outStockItems"
                            border
                            style="width: 100%"
                            show-summary
                        >
                            <el-table-column label="物料编码" width="100">
                                <template #default="scope">{{scope.row.materialCode}}</template>
                            </el-table-column>
                            <el-table-column label="物料名称" width="130">
                                <template #default="scope">{{scope.row.materialName}}</template>
                            </el-table-column>
                            <el-table-column label="规格" width="120">
                                <template #default="scope">{{scope.row.materialSpecs}}</template>
                            </el-table-column>
                            <el-table-column label="物料类别" width="120">
                                <template #default="scope">{{scope.row.materialTypeName}}</template>
                            </el-table-column>
                            <el-table-column label="单位" width="80">
                                <template #default="scope">{{scope.row.unitName}}</template>
                            </el-table-column>
                            <el-table-column label="出库数量" prop="qty">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.qty"
                                        style="width: 100%"
                                        :step="1"
                                        controls-position="right"
                                    ></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="出库单价" prop="price">
                                <template #default="scope">
                                    <el-input-number
                                        v-model="scope.row.price"
                                        style="width: 100%"
                                        :step="0.01"
                                        controls-position="right"
                                    ></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="金额" width="90" prop="totalAmount">
                                <template
                                    #default="scope"
                                >{{scope.row.totalAmount=scope.row.qty*scope.row.price}}</template>
                            </el-table-column>
                            <el-table-column label="备注">
                                <template #default="scope">
                                    <el-input v-model="scope.row.remarks" style="width: 100%" />
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="80">
                                <template #default="scope">
                                    <el-button
                                        size="small"
                                        @click="deleteRow(scope.$index, scope.row)"
                                    >移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="handleBeforeClose">取 消</el-button>
            <el-button
                v-if="mode != 'show'"
                type="primary"
                :loading="isSaveing"
                @click="submit(1)"
            >暂 存</el-button>
            <el-button
                v-if="mode != 'show'"
                type="primary"
                :loading="isSaveing"
                @click="submit(2)"
            >保 存</el-button>
        </template>

        <template>
            <el-dialog
                v-model="materialState"
                title="选择商品"
                :width="1300"
                :center="true"
                append-to-body
				destroy-on-close
                style="height: 480px"
            >
                <el-row style="margin-bottom: 10px;">
                    <material-choice-dialog ref="scMaterialChoice" :queryList="{WarehouseId:entityObj.warehouses.warehouseId}" :queryType="'out-stock/stockmaterial'"></material-choice-dialog>
                </el-row>
                <template #footer >
                    <el-button @click="materialState = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setMaterialChoice">确定</el-button>
                </template>
            </el-dialog>
        </template>

        <!-- 销售订单 -->
        <template>
            <el-dialog v-model="saleOrderState" title="选择销售单出库" :width="1300" :center="true" append-to-body style="height: 540px">
                <el-row style="margin-bottom: 10px;">
                    <sc-pos-sale-order-choice ref="scPosSaleOrderChoice" :defaultQueryList="posSaleOrderQueryList"></sc-pos-sale-order-choice>
                </el-row>
                <template #footer>
                    <el-button @click="saleOrderState = false">取 消</el-button>
                    <el-button type="primary" :loading="isSaveing" @click="setPosSaleOrderChoice">确定</el-button>
                </template>
            </el-dialog>
        </template>
    </el-dialog>
</template>



<script>
import tool from "@/utils/tool";
import MaterialChoiceDialog from "./materialchoice";
export default {
    emits: ["success", "closed"],
	components: {
	   MaterialChoiceDialog
	},
    data() {
        return {
            mode: "Add",
            titleMap: {
                Add: "新增",
                Edit: "编辑",
                Show: "查看",
            },
            entityObj: {
                outStockItems: [],
            },
            materialState: false,
            saleOrderState:false,
            storeState: false,
            queryList: {},
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            //验证规则
            rules: {
                outStockDate: [
                    { required: true, type: "string", message: "请填写" },
                ],
                warehouses: [
                    { required: true, type: "object", message: "请填写" },
                ],
                outStockType: [
                    { required: true, type: "number", message: "请填写" },
                ],
                customName: [
                    { required: true, type: "string", message: "请填写" },
                ],
                crName: [{ required: true, type: "string", message: "请填写" }],
                crDate: [{ required: true, type: "string", message: "请填写" }],
                createType: [
                    { required: true, type: "number", message: "请填写" },
                ],
                sourceType: [
                    { required: true, type: "number", message: "请填写" },
                ],
                outStockItems: [
                    {
                        required: true,
                        type: "array",
                        message: "请填写",
                        trigger: "change",
                    },
                ],
            },
            supplierProps: {
                label: "supplierName",
                value: "supplierId",
            },
            warehouseProps: {
                label: "warehouseName",
                value: "warehouseId",
            },
            materialProps: {
                label: "materialCode",
                value: "materialId",
                items: "materialItems",
            },
            posSaleOrderQueryList:{},
            optionsCreateType: [],
            optionsSourceType: [],
            optionsoutStockType: [],
            itemsData: [],
        };
    },
    computed: {},
    methods: {
        //显示=
        async open(mode = "Add") {
            this.mode = mode;
            this.visible = true;

            return this;
        },
        handleBeforeClose() {
            this.$confirm("信息未保存,确定要关闭吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.visible = false;
                })
                .catch(() => {
                    // 用户点击了取消按钮，不执行关闭
                });
        },
        //表单提交方法
        submit(status) {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    this.isSaveing = true;
                    try {
                        this.entityObj.warehouseId =
                            this.entityObj.warehouses.warehouseId;
                        var returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                this.mode == "Add"
                                    ? "out-stock/create"
                                    : "out-stock/update",
                                { ...this.entityObj, auditStatus: status }
                            );
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$emit("fatherMethod");
                            this.isSaveing = false;
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                        }
                    } catch (error) {
                        this.loading = false;
                        this.isSaveing = false;
                        return false;
                    }
                }
            });
        },
        //表单注入数据
        async setData(id) {
            if (id && id > 0) {
                try {
                    var returnValue = await this.$API.auth.GetProcessApi.get(
                        "out-stock/detail/" + id,
                        {}
                    );
                    if (returnValue.status == 200) {
                        this.entityObj = returnValue.response;
                        this.entityObj.suppliers = {
                            supplierId: this.entityObj.supplierId,
                            supplierName: this.entityObj.supplierName,
                        };
                        this.entityObj.warehouses = {
                            warehouseId: this.entityObj.warehouseId,
                            warehouseName: this.entityObj.warehouseName,
                        };
                    } else {
                        this.$message.error("操作失败:" + returnValue.msg);
                    }
                } catch (error) {
                    this.loading = false;
                    return false;
                }
            }
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post(
                    "base-dictionary/options",
                    { Codes: ["OutStockType", "CreateType", "SourceType"] }
                );
                if (returnValue.status == 200) {
                    this.optionsCreateType = returnValue.response.find(
                        (p) => p.code == "CreateType"
                    ).optionsDetails;
                    this.optionsSourceType = returnValue.response.find(
                        (p) => p.code == "SourceType"
                    ).optionsDetails;
                    this.optionsoutStockType = returnValue.response.find(
                        (p) => p.code == "OutStockType"
                    ).optionsDetails;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        addMaterial() {
			if(this.entityObj.warehouses==undefined){
				 this.$message.error("请选择出库仓库");
			}else{
				this.materialState = true;
			}

            // this.materialState = true;
        },
        addSaleOrder() {
			if(this.entityObj.warehouses==undefined){
				 this.$message.error("请选择出库仓库");
			}else{
				this.saleOrderState = true;
			}
        },
        deleteRow(index) {
            this.entityObj.outStockItems.splice(index, 1);
        },
        setMaterialChoice() {
            let materials = this.$refs.scMaterialChoice.selectionRows;
            materials.map((p) => {
                debugger;
                this.entityObj.outStockItems.push({
                    materialId: p.materialId,
                    materialCode: p.materialCode,
                    materialName: p.materialName,
                    materialSpecs: p.materialSpecs,
                    materialTypeId: p.materialTypeId,
                    materialTypeName: p.materialTypeName,
                    unitName: p.unitName,
                    qty: 0,
                    price: 0,
                    totalAmount: 0,
                    remarks: "",
                    materialItemId: p.materialItemId,
                });
            });
            this.materialState = false;
        },
        //选择销售订单
        setPosSaleOrderChoice() {
            let materials = this.$refs.scPosSaleOrderChoice.selectionRows;
            if(materials.some(p=>!p.materialItemId||p.materialItemId==0)){
                this.$message.error("销售单中商品还未绑定物料,请先在物料对照管理中新增相关的对照关系");
                return;
            }

            materials.map((p) => {
                this.entityObj.outStockItems.push({
                    materialId: p.materialId,
                    materialCode: p.materialCode,
                    materialName: p.materialName,
                    materialSpecs: p.materialSpecs,
                    materialTypeId: p.materialTypeId,
                    materialTypeName: p.materialTypeName,
                    unitName: p.unitName,
                    qty: p.orderQty,
                    price: p.salePrice,
                    totalAmount: 0,
                    remarks: "",
                    materialItemId: p.materialItemId,
                });
            });
            this.saleOrderState = false;
        },
        purchaseUnityChange(value) {
            this.entityObj.purchaseRealName = this.optionsPurchaseUnity.find(
                (p) => p.purchaseUnityId == value
            ).realName;
            this.entityObj.purchaseMobile = this.optionsPurchaseUnity.find(
                (p) => p.purchaseUnityId == value
            ).mobile;
        },
    },
    async mounted() {
        this.entityObj.outStockDate = tool.formatDate(new Date(), 1);
        this.entityObj.crName = tool.data.get("USER_INFO").Name;
        this.entityObj.crDate = tool.formatDate(new Date());
        await this.initOptions();
    },
};
</script>

<style></style>
